﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Resources;

namespace XamlingCore.Infrastructure.Resource
{
    public static class ResourceLoader
    {
        /// <summary>
        /// The target file must be set to "Resource" Build Action
        /// </summary>
        /// <param name="assemblyName">E.g. SilverlightMainApp</param>
        /// <param name="dataPath">E.g. Data/SomeSampleData.xml</param>
        /// <returns></returns>
        public static string LoadStringResource(string assemblyName, string dataPath)
        {
            StreamResourceInfo sr = Application.GetResourceStream(
                new Uri(string.Format("/{0};component/{1}", assemblyName, dataPath), UriKind.Relative));

            using (StreamReader reader = new StreamReader(sr.Stream))
            {
                return reader.ReadToEnd();
            } 
        }

        public static string LoadStringResource(string dataPath)
        {
            StreamResourceInfo sr = Application.GetResourceStream(
                new Uri(dataPath, UriKind.Relative));

            using (StreamReader reader = new StreamReader(sr.Stream))
            {
                return reader.ReadToEnd();
            }
        }

        public static byte[] LoadResource(string assemblyName, string dataPath)
        {
            StreamResourceInfo sr = Application.GetResourceStream(
                new Uri(string.Format("/{0};component/{1}", assemblyName, dataPath), UriKind.Relative));

            var b = new byte[sr.Stream.Length];
            sr.Stream.Read(b, 0, b.Length);

            return b;
        }
    }
}
